/*
 * @Author      : daguan814
 * @date        : 2022/9/20 21:16
 * @Description :
 */


package com.example.newsbackgroundmanagement.controller;


import com.example.newsbackgroundmanagement.entity.BaseModel;
import com.example.newsbackgroundmanagement.util.ApiConstant;
import com.example.newsbackgroundmanagement.util.FtpUtil;
import com.example.newsbackgroundmanagement.util.TDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * 通用，文件上传下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${dxb.path}")
    private String basepath;

    @Value("${dxb.reUrl}")
    private String reUrl;


    @Value("${file.upload.path}")
    private String fileSavePath;

    @Value("${file.coming.path}")
    private String fileComingPath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */

    @RequestMapping(value = "/upload")
    public BaseModel upload(@RequestParam("uploadFile") MultipartFile file) throws IOException {  //参数名必须和前端的name保持一致
        System.out.println(file);
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，避免文件重复造成文件覆盖 suffix:后缀名
        String newfilename = UUID.randomUUID().toString() + suffix;

        File uploadFileSaveDir = new File(reUrl);
        System.out.println("上传文件的存放目录："+uploadFileSaveDir.getAbsolutePath());
        if(!uploadFileSaveDir.exists()){
            // 递归生成文件夹
            uploadFileSaveDir.mkdirs();
        }


        //file 是一个临时文件，需要把它转存在指定位置,否则本次请求结束之后这个临时文件会消失
//        file.transferTo(new File(reUrl + newfilename));

        BaseModel baseModel=new BaseModel(10000,"文件上传成功！");
        baseModel.setData(newfilename);
        return baseModel;
    }


    @RequestMapping(value ="/download")
    public void download(String name, HttpServletResponse response) throws IOException {

        //通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(new File(basepath + name));

        //输出流，将文件写回浏览器，在浏览器里面展示图片
        ServletOutputStream outputStream = response.getOutputStream();

        int len= 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }

        outputStream.close();
        fileInputStream.close();


    }



    @RequestMapping(value ="uploadImg")
    public BaseModel updloadImg(@RequestParam("uploadFile") MultipartFile upload){
        try {
            //获取文件上传路径
            String path = fileSavePath;
            System.out.println("文件上传路径为："+path);
            File file = new File(path);
            //判断不存在该目录就创建
            if (!file.exists()){
                file.mkdirs();
            }
            //获取文件名
            String filename = upload.getOriginalFilename();
            System.out.println(filename);
            //起别名
            String s = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            filename=s+filename;
            //开始上传
            upload.transferTo(new File(file,filename));

            BaseModel baseModel = new BaseModel(20000,"图片上传成功！");
            baseModel.setData(fileComingPath+filename);
            System.out.println("最终文件的访问路径："+baseModel.getData());
            return baseModel;
        } catch (IOException e) {
            System.out.println("图片上传失败"+upload.getOriginalFilename());
            return null;
        }
    }

    @RequestMapping(value ="uploadPicture")
    public BaseModel uploadPicture(@RequestParam("uploadFile") MultipartFile uploadFile) {
        //1、给上传的图片生成新的文件名
        //1.1获取原始文件名
        String oldName = uploadFile.getOriginalFilename();
        //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
        String newName = TDUtils.getImageName();
        assert oldName != null;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));

        //2、把图片上传到图片服务器
        //2.1获取上传的io流
        InputStream input = null;
        try {
            input = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }


        //2.2调用FtpUtil工具类进行上传
        return FtpUtil.putImages(input,newName);
    }






    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    public BaseModel uploadImage(@RequestParam("uploadFile") MultipartFile file) throws IOException{
        BaseModel baseModel;
        if(file != null){
            baseModel=new BaseModel(1,uploadFile(file));
            return baseModel;
        }else{
              baseModel=new BaseModel(2,"文件不存在");
            return baseModel;
        }
    }



    public String uploadFile(MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));


        // 解决中文问题，liunx下中文路径，图片显示问题
        fileName = UUID.randomUUID().toString().replace("-", "") + suffixName;

        // 返回客户端 文件地址 URL
        String url = "http://8.134.162.148:8081/"+ fileName;
        // String url = "localhost:8090"+"/upload/" + fileName;

        File dest = new File(ApiConstant.UPLOAD_PATH + fileName);

        // File dest = new File(ApiConstant.DEV_UPLOAD_PATH + fileName);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        file.transferTo(dest);

        // return new ResultBuilder<>().setData(MapUtil.returnMap("url",url)).build();

        return url;
    }




}